package mya.mes.mdc.logic.tag.impl;

import com.alibaba.fastjson.JSONObject;
import mya.mes.mdc.local.mongodb.MongoDbService;
import mya.mes.mdc.logic.tag.TagService;
import mya.mes.mdc.model.excel.ExcelData;
import mya.mes.mdc.model.tag.MdcTag;
import mya.mes.mdc.model.tag.ViewTagHolder;
import mya.mes.mdc.model.tag.convert.TagHolderUpdate;
import mya.mes.mdc.model.tag.util.TagHolder;
import mya.mes.mdc.mongodb.DbCollections;
import mya.mes.mdc.mongodb.Mongo;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.stream.Collectors;

public class TagServiceImpl implements TagService {
    private static final Logger logger = LoggerFactory.getLogger(TagServiceImpl.class);
    private final String TAG_DEF_PREFX = "TAG_DEF_CVS_";
    private final String TAG_ALARM_DEF_PREFX = "TAG_DEF_ALARM_";

    private final String MDC_TAG_COLLECTION = "MDC_TAG";


    @Override
    public void updateTagHolder(String shop, String area, ExcelData excelData) {
        TagHolderUpdate update = new TagHolderUpdate();
        List<MdcTag> list = update.process(excelData);
        TagHolder.getInstance().update(list);
//        ViewTagHolder.getInstance().build(new TagHolder());
        List<MdcTag> listToSave = TagHolder.getInstance().asList();
        List<JSONObject> tagDefList = listToSave.stream()
                .map(mdcTag -> {
                    if (mdcTag == null) {
                        return null;
                    }
                    JSONObject doc = mdcTag.toJson();
                    doc.put("_id", mdcTag.tagName);
                    return doc;
                }).filter(p -> {
                    return p != null;
                }).collect(Collectors.toList());
        MongoDbService mongoDbService = Mongo.getInstance().getMongoDbService();
        //删除已经保存的MDC_TAG
        boolean deleteResult = mongoDbService.deleteCollection(DbCollections.MDC_TAG);
        if (deleteResult) {
            mongoDbService.saveByCollectionName(DbCollections.MDC_TAG, tagDefList);
        }
    }


    @Override
    public void loadTagHolder() {
        MongoDbService mongoDbService = Mongo.getInstance().getMongoDbService();
        List<Document> documents = mongoDbService.queryMdcTag(DbCollections.MDC_TAG);
        List<MdcTag> mdcTagList = documents.stream()
                .map(json -> new MdcTag(new JSONObject(json))).collect(Collectors.toList());
        TagHolder.getInstance().init(mdcTagList);
    }

}
